<?php
require_once 'Zend/Db/Table/Abstract.php';

class SearchDataCache extends Zend_Db_Table_Abstract {
	
	const STATUS_ACTIVE = 'active';
	const STATUS_EXPIRED = 'expired';
	const PAGE_SIZE = 10;
	
	protected $_primary = 'id';
	protected $_name = "search_data_cache";
	
	/**
	 * Find active search data by given category and keyword.
	 * 
	 * @param $category
	 * @param $keyword
	 * @param page
	 * @return return search data cached
	 */
	public function findActiveByCategoryKeywordAndPage($category, $keyword, $page) {
		$select = $this->select()->where('upper(category)=upper(?)', $category)
		->where('upper(keyword)=upper(?)', $keyword)
		->where('page=?', $page)
		->where('status=?', self::STATUS_ACTIVE);
		return $this->fetchRow($select);
	}
	
	/**
	 * 
	 * @param $category
	 * @param $keyword
	 * @param $page
	 * @param $data
	 * @param $has_next if has next page
	 * @return return saved search data
	 */
	public function cacheSearchData($category, $keyword, $page, $data, $has_next, $created, $expired) {
		$obj = $this->findActiveByCategoryKeywordAndPage($category, $keyword, $page);
		if (!isset($obj)) {
			$obj = $this->createRow();
			$obj->category = $category;
			$obj->keyword = $keyword;
			$obj->page = $page;
			$obj->data = $data;
			$obj->has_next = $has_next;
			$obj->created = $created;
			$obj->expired = $expired;
			$id = $obj->save();
		}
		return $obj;
	}
	
	/**
	 * Expire search data.
	 * 
	 * @param $date
	 */
	public function expireSearchData($date) {
		echo $date;
		$select = $this->select()->where('status=?', self::STATUS_ACTIVE)
		->where('expired<=?', $date);
		$rows = $this->fetchAll($select);
		foreach ($rows as $row) {
			$row->status = self::STATUS_EXPIRED;
			$row->save();
		}
	}
}
?>